const service = require("../service/label.service");

const verifyLabelExists = async (ctx, next) => {
  // 1.取出要添加的所有的标签
  const { labels } = ctx.request.body;

  // 2.判断每一个标签在label表中是否存在，不存在的话创建标签
  const newLabels = [];
  for (let name of labels) {
    //取数据库中判断是否存在标签
    const labelResult = await service.getLabelByName(name);
    const label = { name };
    // 判断labelResult是有值
    if (!labelResult) {
      // 创建标签数据
      const result = await service.create(name);

      label.id = result.insertId;
    } else {
      label.id = labelResult.id;
    }
    // 每个label中有id和name，放到newLabels
    newLabels.push(label);
  }
  ctx.labels = newLabels;
  await next();
};

module.exports = {
  verifyLabelExists,
};
